﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;

namespace MiserDB.MySql
{
    public sealed class NHibernateHelper
    {
        private const string CurrentSessionKey = "nhibernate.current_session";
        private static ISessionFactory sessionFactory;

        static NHibernateHelper()
        {
            var cfg = new NHibernate.Cfg.Configuration().Configure();
            sessionFactory = cfg.BuildSessionFactory();
        }

        public static ISession GetCurrentSession()
        {
            //System.Web.HttpContext context = System.Web.HttpContext.Current;
            //ISession currentSession = context.Items[CurrentSessionKey] as ISession;
            //if (currentSession == null)
            //{
            //    currentSession = sessionFactory.OpenSession();
            //    context.Items[CurrentSessionKey] = currentSession;
            //}
            //return currentSession;
            return sessionFactory.OpenSession();
        }

        public static void CloseSession()
        {
            System.Web.HttpContext context = System.Web.HttpContext.Current;
            ISession currentSession = context.Items[CurrentSessionKey] as ISession;
            if (currentSession == null)
            {
                return;
            }
            currentSession.Close();
            context.Items.Remove(CurrentSessionKey);
        }

        public static void CloseSessionFactory()
        {
            if (sessionFactory != null)
            {
                sessionFactory.Close();
            }
        }
    }
}
